package com.jy.rhin.infra.cda.feign;

import com.jy.api.misc.MiscAPI;
import com.jy.api.misc.dto.DaiMaDto;
import com.jy.api.misc.dto.WSSYBMXTDaiMaDto;
import com.jy.api.misc.dto.ZhiYuMXCXDto;
import com.jy.common.StringUtil;
import com.jy.framework.base.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dhl
 * @date 2023/01/06
 */
@Component
@Slf4j
public class ShuYuService {

    @Resource
    private MiscAPI miscApi;

    private static final String FILTER_EMPTY_KEY = "NULL";

    private static final String VERTICAL = "|";
    private static final String VERTICAL_TRANSLATION = "\\|";


    /**
     * 根据值域标识符和code获取value
     *
     * @param zhiJiBSFList
     * @return
     */
    public Map<String, List<DaiMaDto>> getValueByCode(ZhiYuMXCXDto[] zhiJiBSFList) {
        long no = System.currentTimeMillis();
        ZhiYuMXCXDto[] distinctZhiJiBSFList = zhiJiBSFListDistinct(zhiJiBSFList);
        Result<List<WSSYBMXTDaiMaDto>> listResult = miscApi.getValueByCode(distinctZhiJiBSFList, judgeMode(distinctZhiJiBSFList));
        long no1 = System.currentTimeMillis();
        log.debug("shuyu接口调用耗时：{}", no1 - no);
        if (listResult != null && listResult.isSuccess() && !CollectionUtils.isEmpty(listResult.getData())) {
            return listResult.getData().stream().filter(Objects::nonNull).collect(Collectors.toMap(
                    wssybmxtDaiMaDto -> StringUtils.defaultIfBlank(wssybmxtDaiMaDto.getBiaoShiFu(), FILTER_EMPTY_KEY),
                    wssybmxtDaiMaDto -> !CollectionUtils.isEmpty(wssybmxtDaiMaDto.getDaiMaVoList()) ? new ArrayList<>(wssybmxtDaiMaDto.getDaiMaVoList()) : Collections.emptyList(),
                    (t, t2) -> t));
        }
        return new HashMap<>(0);
    }

    /**
     * 根据值域标识符获取代码（列表）
     */
    public Map<String, List<DaiMaDto>> getDaiMaByZJBSFList(Set<String> zhiJiBSFList) {
        long no = System.currentTimeMillis();
        String[] zhiJiBSFS = zhiJiBSFList.toArray(new String[0]);
        Result<List<WSSYBMXTDaiMaDto>> listResult = miscApi.getDaiMaByZJBSFList(zhiJiBSFS);
        long no1 = System.currentTimeMillis();
        log.debug("shuyu接口调用耗时：{}", no1 - no);
        if (listResult != null && listResult.isSuccess() && !CollectionUtils.isEmpty(listResult.getData())) {
            return listResult.getData().stream().filter(Objects::nonNull).collect(Collectors.toMap(
                    wssybmxtDaiMaDto -> StringUtils.defaultIfBlank(wssybmxtDaiMaDto.getBiaoShiFu(), FILTER_EMPTY_KEY),
                    wssybmxtDaiMaDto -> !CollectionUtils.isEmpty(wssybmxtDaiMaDto.getDaiMaVoList()) ? new ArrayList<>(wssybmxtDaiMaDto.getDaiMaVoList()) : Collections.emptyList(),
                    (t, t2) -> t));
        }
        return new HashMap<>(0);
    }

    /**
     * 相同值集标识符封装到一起，包含的codeList去重
     *
     * @return
     */
    private ZhiYuMXCXDto[] zhiJiBSFListDistinct(ZhiYuMXCXDto[] zhiJiBSFList) {
        Map<String, List<String>> map = new HashMap<>(8);
        //相同值集标识符封装
        for (ZhiYuMXCXDto zhiYuMXCXDto : zhiJiBSFList) {
            String zhiJiBSF = zhiYuMXCXDto.getZhiJiBSF();
            map.computeIfAbsent(zhiJiBSF, key -> new ArrayList<>()).addAll(buildCodeList(zhiYuMXCXDto.getCodeList()));
        }
        List<ZhiYuMXCXDto> list = new ArrayList<>();
        map.forEach((key, value) -> {
            //codeList去重
            List<String> collect = value.stream().distinct().collect(Collectors.toList());
            ZhiYuMXCXDto zhiYuMXCXDto = new ZhiYuMXCXDto();
            zhiYuMXCXDto.setZhiJiBSF(key);
            zhiYuMXCXDto.setCodeList(codeContainsVertical(collect));
            list.add(zhiYuMXCXDto);
        });
        return list.toArray(new ZhiYuMXCXDto[0]);
    }

    /**
     * 涉及到ICD-10直接查询数据库速度更快
     * 查询模式1 查询缓存 ，2查询数据库
     *
     * @param zhiJiBSFList
     * @return
     */
    private Integer judgeMode(ZhiYuMXCXDto[] zhiJiBSFList) {
        Map<String, List<String>> map = Arrays.stream(zhiJiBSFList).
                collect(Collectors.toMap(ZhiYuMXCXDto::getZhiJiBSF, ZhiYuMXCXDto::getCodeList));
        return map.containsKey("ICD-10") ? 2 : 1;
    }


    /**
     * 封装codelist
     *
     * @param codelist
     * @return
     */
    public List<String> buildCodeList(List<String> codelist) {
        return !CollectionUtils.isEmpty(codelist) ? new ArrayList<>(codelist) : Collections.emptyList();
    }

    /**
     * 判断code是否是多个选项
     *
     * @return
     */
    private List<String> codeContainsVertical(List<String> codeList) {
        if (CollectionUtils.isEmpty(codeList)) {
            return codeList;
        }
        List<String> list = new ArrayList<>();
        codeList.forEach(code -> {
            if(!StringUtil.isNullOrEmpty(code)){
                if (code.contains(VERTICAL)) {
                    String[] split = code.split(VERTICAL_TRANSLATION);
                    List<String> codeListNew = Arrays.asList(split);
                    list.addAll(codeListNew);
                } else {
                    list.add(code);
                }
            }

        });
        return list;
    }
}
